//
//  NANavigationController.m
//  nanavigation
//
//  Created by zhangyue on 16/4/6.
//  Copyright © 2016年 zeroflow. All rights reserved.
//

#import "UIViewController+NANav.h"
#import "NASubNavigationController.h"
#import "InTouchView.h"
static void* const titleObserverContext = (void *)&titleObserverContext;
@interface NANavigationController()<UINavigationControllerDelegate,UIGestureRecognizerDelegate,NASubNavBackPanEnbaleDelegate>{
    BOOL backEnbale;
    UILabel * firstNavBarTitleLabel;
}
@property (strong ,nonatomic) UIPanGestureRecognizer *backPanGesture;
@property (strong ,nonatomic) id backGestureRecognizerDelegate;
@property (strong ,nonatomic) NSMutableArray<UIViewController*> *m_viewControllerArray;
@property (strong ,nonatomic) NSMutableArray<UIViewController*> *m_bagViewControllerArray;
@end
@implementation NANavigationController


- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self){
        [self arrayInital];
    }
    return self;
}

- (id)initWithRootViewController:(UIViewController *)rootViewController{
    self =  [super init];
    if (self){
        [self arrayInital];
    }
    return self;
}

- (id)init{
    self = [super init];
    if (self) {
        [self arrayInital];
    }
    return self;
}

- (void)arrayInital{
    self.m_viewControllerArray = [[NSMutableArray alloc]initWithCapacity:10];
    self.m_bagViewControllerArray = [[NSMutableArray alloc]initWithCapacity:10];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationBarHidden:YES];
    self.delegate = self;
    
    if (self.viewControllers.count) {
        UIViewController * rootViewController = self.viewControllers.firstObject;
        
        NASubNavigationController * nanavc = [[NASubNavigationController alloc]init];
        nanavc.na_delegate = self;
        
        [rootViewController setNaNavigationController:self];
        UIViewController * bagViewController = [self bagNavWithViewController:rootViewController nav:nanavc];
        self.viewControllers = @[bagViewController];

        [self.m_viewControllerArray addObject:rootViewController];
    }
    
    self.backGestureRecognizerDelegate = self.interactivePopGestureRecognizer.delegate;
    self.backPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.backGestureRecognizerDelegate action:NSSelectorFromString(@"handleNavigationTransition:")];
    self.backPanGesture.delegate = self;
    self.backPanGesture.maximumNumberOfTouches = 1;}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([self.m_bagViewControllerArray containsObject:viewController]) {
        if ([viewController isEqual:self.m_bagViewControllerArray.lastObject]) {
            
        }else{
            NSUInteger index = [self.m_bagViewControllerArray indexOfObject:viewController];
            [self.m_bagViewControllerArray removeObjectsInRange:NSMakeRange(index + 1, self.m_bagViewControllerArray.count - index - 1)];
        }
    }else{
        [self.m_bagViewControllerArray addObject:viewController];
    }
    
    if (self.m_bagViewControllerArray.count <= 1) {
        [self.view removeGestureRecognizer:self.backPanGesture];
    }
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    CGPoint point = [touch locationInView:self.view];
    return point.x < 25;
}
#pragma mark - panEnable settings
- (void)switchMainNavBackPanEnable:(BOOL)enable{
    if (!enable || self.m_bagViewControllerArray.count <= 1) {
        [self.view removeGestureRecognizer:self.backPanGesture];
    } else {
        [self.view addGestureRecognizer:self.backPanGesture];
    }
}
- (void)didSubNavShowViewController:(UIViewController *)viewController{
    if ([self.m_viewControllerArray containsObject:viewController]) {
        if ([viewController isEqual:self.m_viewControllerArray.lastObject]) {
            
        }else{
            NSUInteger index = [self.m_viewControllerArray indexOfObject:viewController];
            [self.m_viewControllerArray removeObjectsInRange:NSMakeRange(index + 1, self.m_viewControllerArray.count - index - 1)];
        }
    }else{
        [self.m_viewControllerArray addObject:viewController];
    }
}
#pragma mark - push
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [viewController setNaNavigationController:self];
    if (self.m_viewControllerArray.lastObject.transparentNavigationBarBool ^
        viewController.transparentNavigationBarBool) {
        NASubNavigationController * nanavc = [[NASubNavigationController alloc]init];
        nanavc.na_delegate = self;
        UIViewController * bagViewController = [self bagNavWithViewController:viewController nav:nanavc];
        bagViewController.hidesBottomBarWhenPushed = viewController.hidesBottomBarWhenPushed;
        [super pushViewController:bagViewController animated:animated];
        [self.m_bagViewControllerArray addObject:bagViewController];
    }else{
        NASubNavigationController * subNav = [self.m_bagViewControllerArray lastObject].childViewControllers[0];
        [subNav pushViewController:viewController animated:animated];
    }
    
    //config leftBarButton
    
    UIImage *image = [UIImage imageNamed:@"iconfont-fanhui"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView * backImageView = [[UIImageView alloc]initWithImage:image];
    InTouchView * customBackView = [[InTouchView alloc]initWithFrame:CGRectZero];
    
    [backImageView setTintColor:viewController.naNavigationController.navigationBar.tintColor];
    backImageView.frame = CGRectOffset(backImageView.frame, 0, 9);
    
    UIViewController * lastViewController = self.m_viewControllerArray.lastObject;
    if (lastViewController.navigationItem.backBarButtonItem.title && self.showBackTitle) {
        UILabel * backLabel = [[UILabel alloc] init];
        backLabel.text = lastViewController.navigationItem.backBarButtonItem.title;
        backLabel.font = [UIFont systemFontOfSize:15];
        backLabel.textColor = viewController.naNavigationController.navigationBar.tintColor;
        [backLabel sizeToFit];
        backLabel.frame = CGRectOffset(backLabel.frame, backImageView.frame.size.width + 1, 13);
        customBackView.frame = CGRectMake(0, 0, backImageView.frame.size.width + 5 + backLabel.frame.size.width, 44);
        [customBackView addSubview:backLabel];
    }else{
        customBackView.frame = CGRectMake(0, 0, backImageView.frame.size.width, 44);
    }
    [customBackView addSubview:backImageView];
    [customBackView setGestureRecognizersBlock:^{
        [self backClicked:viewController];
    }];
    viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:customBackView];
    
    [self.m_viewControllerArray addObject:viewController];
}

#pragma mark - pop

- (NSArray<UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated {
    NASubNavigationController * subNav = [self.m_bagViewControllerArray firstObject].childViewControllers[0];
    if (self.m_bagViewControllerArray.count > 1) {
        subNav.viewControllers = @[subNav.viewControllers.firstObject];
    }else{
        [subNav popToRootViewControllerAnimated:animated];
    }
    return [super popToRootViewControllerAnimated:animated];
}

- (NSArray<UIViewController *> *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if ([self.m_viewControllerArray containsObject:viewController]) {
        [viewController.navigationController popToViewController:viewController animated:animated];
        return [super popToViewController:viewController.navigationController.parentViewController animated:animated];
    }
    return nil;
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
    if (self.m_viewControllerArray.count > 1) {
        UIViewController * vcBeforeLastVc = self.m_viewControllerArray[self.m_viewControllerArray.count - 2];
        UIViewController * lastVc = self.m_viewControllerArray.lastObject;
        if (vcBeforeLastVc.transparentNavigationBarBool ^
            lastVc.transparentNavigationBarBool) {
            return [super popViewControllerAnimated:animated];
        }else{
            NASubNavigationController * subNav = [self.m_bagViewControllerArray lastObject].childViewControllers[0];
            return [subNav popViewControllerAnimated:animated];
        }
    }else{
        return [super popViewControllerAnimated:animated];
    }
}
#pragma mark - pack Nav
- (UIViewController*)bagNavWithViewController:(UIViewController*)viewController nav:(NASubNavigationController*)nanavc{
    if (viewController.transparentNavigationBarBool) {
        [nanavc.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        [nanavc.navigationBar setShadowImage:[UIImage new]];
    }
    UIViewController * bagViewController = [[UIViewController alloc] init];
    nanavc.viewControllers = @[viewController];
    [bagViewController addChildViewController:nanavc];
    [bagViewController.view addSubview:nanavc.view];
    return bagViewController;
}
#pragma mark - others
- (void)backClicked:(UIViewController*)sender{
    if (sender && sender.didBackClicked) {
        sender.didBackClicked();
    }else{
        [self popViewControllerAnimated:YES];
    }
}
#pragma mark -
- (NSArray*)viewControllerArray{
    return [self.m_viewControllerArray copy];
}
- (void)removeViewController:(UIViewController*)vc{
    [self.m_viewControllerArray removeObject:vc];
}
@end
